package com.dldata.devtools30.controller.api;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.controller.DevBase30Controller;
import com.dldata.devtools30.entity.DevtApiMainEntity;
import com.dldata.devtools30.entity.DevtApiSubEntity;
import com.dldata.devtools30.entity.DevtApiTjoptEntity;
import com.dldata.devtools30.entity.DevtApiTjoptcheckEntity;
import com.dldata.devtools30.service.api.DevtApiMainEntityService;
import com.dldata.devtools30.service.api.DevtApiSubEntityService;
import com.dldata.devtools30.service.api.DevtApiTjoptEntityService;
import com.dldata.devtools30.service.api.DevtApiTjoptcheckEntityService;
import com.dldata.devtools30.utils.DateUtil;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import com.dldata.devtools30.utils.dataexport.DataExportUtil;
import com.dldata.devtools30.utils.dataexport.TableConfig;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/DevtApiSubEntityController")
public class DevtApiSubEntityController extends DevBase30Controller {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private DevtApiTjoptEntityService devtApiTjoptEntityService;
    @Autowired
    private DevtApiTjoptcheckEntityService devtApiTjoptcheckEntityService;
    @Autowired
    private DevtApiSubEntityService devtApiSubEntityService;
    @Autowired
    private DevtApiMainEntityService apiMainEntityService;

    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAll(String pid, String cancel, String dmorsql , String apisubtype) {

        try {

            List<DevtApiSubEntity> devtApiSubEntities = new ArrayList<DevtApiSubEntity>();
            if (!StringUtil.isEmptyOrLength0(pid)) {
                devtApiSubEntities = devtApiSubEntityService.getAllDataById(pid);
            } else {
                devtApiSubEntities = devtApiSubEntityService.getAllData();
            }
            devtApiSubEntities=devtApiSubEntities.stream().filter(
                    pFunctionsubEntity -> {
                        if(!StringUtil.isEmptyOrLength0(apisubtype)){
                           if(!pFunctionsubEntity.getLx().equals(Integer.valueOf(apisubtype))){
                               return false;
                           }
                        }
                        return  StringUtil.isEmptyOrLength0(dmorsql)|| pFunctionsubEntity.getMc().indexOf(dmorsql)>-1
                                ||  pFunctionsubEntity.getDm().indexOf(dmorsql)>-1||pFunctionsubEntity.getSql().indexOf(" "+dmorsql.trim())>-1;
                    }
            ).collect(Collectors.toList());

            if("1".equals(cancel)){
                devtApiSubEntities = devtApiSubEntities.stream().filter(e -> !e.getCancel()).collect(Collectors.toList());
            }
            if("0".equals(cancel)){
                devtApiSubEntities = devtApiSubEntities.stream().filter(e -> e.getCancel()).collect(Collectors.toList());
            }
            List<Map> datalist=new ArrayList<>();
            for (DevtApiSubEntity entity : devtApiSubEntities) {
                if(entity.getCancel()!=null&&entity.getCancel()){
                    entity.setMc(entity.getMc()+"[已作废]");
                }
                Map<String,Object> data=new HashMap<>();
                data.put("id",entity.getId());
                data.put("xh",entity.getXh());
                data.put("mc",entity.getMc());
                data.put("dm",entity.getDm());
                data.put("lx",entity.getLx());
                data.put("lxmc",DevtApiMainEntityService.FunctionType.valueOf(entity.getLx()).getName());
                data.put("mainid",entity.getMainid());
                data.put("formid",entity.getFormid());
                data.put("datalx",entity.getDatalx());
                data.put("datalxmc",DevtApiMainEntityService.FunctionResultType.valueOf(entity.getDatalx()).getName());
                data.put("bz",entity.getBz());
                data.put("cacheflag",entity.getCacheflag());
                data.put("maxcachetime",entity.getMaxcachetime() );
                data.put("created", DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss",entity.getCreated()));
                data.put("edittime",DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss",entity.getEdittime()));
                data.put("cancel",entity.getCancel());
                data.put("sqltype",entity.getSqltype());

                datalist.add(data);

            }
            return Result.ok(datalist);

        } catch (Exception ex) {
            return Result.error("系统错误，请稍候再试");

        }

    }
    @RequestMapping(value = "/getAllByfl")
    @ResponseBody
    public Result getAllByFl(String flid,  String dmorsql, String apisubtype) {

        try {

            List<DevtApiMainEntity> pFunctionmainEntities=new ArrayList<>();
            if (!StringUtil.isEmptyOrLength0(flid)) {
                 pFunctionmainEntities.addAll(apiMainEntityService.getAllDataById(flid));
            }
            List<DevtApiSubEntity> apiSubEntities = devtApiSubEntityService.getAllData();

            apiSubEntities=apiSubEntities.stream().filter(
                    pFunctionsubEntity -> {
                        if(!StringUtil.isEmptyOrLength0(apisubtype)){
                            if(!pFunctionsubEntity.getLx().equals(Integer.valueOf(apisubtype))){
                                return false;
                            }
                        }
                        return  (StringUtil.isEmptyOrLength0(dmorsql)|| pFunctionsubEntity.getMc().indexOf(dmorsql)>-1
                                ||  pFunctionsubEntity.getDm().indexOf(dmorsql)>-1||pFunctionsubEntity.getSql().indexOf(" "+dmorsql.trim())>-1)
                                &&(pFunctionmainEntities.size()<=0|| pFunctionmainEntities.stream().filter(f->f.getId().equals(pFunctionsubEntity.getMainid())).count()>0);
                    }
            ).collect(Collectors.toList());

            List<Map> datalist=new ArrayList<>();
            for (DevtApiSubEntity entity : apiSubEntities) {
                if(entity.getCancel()!=null&&entity.getCancel()){
                    entity.setMc(entity.getMc()+"[已作废]");
                }
                Map<String,Object> data=new HashMap<>();
                data.put("id",entity.getId());
                data.put("xh",entity.getXh());
                data.put("mc",entity.getMc());
                data.put("dm",entity.getDm());
                data.put("lx",entity.getLx());
                data.put("lxmc",DevtApiMainEntityService.FunctionType.valueOf(entity.getLx()).getName());
                data.put("mainid",entity.getMainid());
                data.put("formid",entity.getFormid());
                data.put("datalx",entity.getDatalx());
                data.put("datalxmc",DevtApiMainEntityService.FunctionResultType.valueOf(entity.getDatalx()).getName());
                data.put("bz",entity.getBz());
                data.put("cacheflag",entity.getCacheflag());
                data.put("maxcachetime",entity.getMaxcachetime() );
                data.put("created",DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss",entity.getCreated()));
                data.put("edittime",DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss",entity.getEdittime()));
                data.put("cancel",entity.getCancel());
                data.put("sqltype",entity.getSqltype());

                datalist.add(data);

            }
            return Result.ok(datalist);

        } catch (Exception ex) {
            return Result.error("系统错误，请稍候再试");

        }

    }
    @RequestMapping(value = "/saveSql")
    @ResponseBody
    public Result saveSql(String sql,String id, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {


        if(StringUtil.isEmptyOrLength0(id) ){
            return Result.error("参数有误");
        }
        try {

            List<DevtApiSubEntity> pFunctionsubEntities= devtApiSubEntityService.getOneData(id);
            if(pFunctionsubEntities==null|| pFunctionsubEntities.size()==0){
                return Result.error("API不存在");
            }
            DevtApiSubEntity pFSubEntity= pFunctionsubEntities.get(0);

            pFSubEntity.setSql(sql);

            pFSubEntity.setEdittime(new java.sql.Date(System.currentTimeMillis()));

            logger.error(JSON.toJSONString(pFSubEntity));
            devtApiSubEntityService.save(pFSubEntity);
            
            return Result.ok();
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error("【执行"+this.getClass().getName()+".saveSql() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }

    }

    
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(HttpServletRequest request,
                       HttpServletResponse response, DevtApiSubEntity pFSubEntity) throws IOException {

        if(StringUtil.isEmptyOrLength0(pFSubEntity.getMc()) ){
            return Result.error("名称不能为空");
        }
        if(StringUtil.isEmptyOrLength0(pFSubEntity.getDm()) ){
            return Result.error("代码不能为空");
        }
        try {


            if(StringUtil.isNullOrSpace(pFSubEntity.getId())){
                pFSubEntity.setId(UUID.randomUUID().toString());
                pFSubEntity.setCreated(new java.sql.Date(System.currentTimeMillis()));
            }else{
                List<DevtApiSubEntity> pFunctionsubEntities= devtApiSubEntityService.getOneData(pFSubEntity.getId());
                if(pFunctionsubEntities==null|| pFunctionsubEntities.size()==0){
                    return Result.error("API不存在");
                }
                pFSubEntity.setCreated(pFunctionsubEntities.get(0).getCreated());
            }

            pFSubEntity.setEdittime(new java.sql.Date(System.currentTimeMillis()));
            if(devtApiSubEntityService.getOneDataByMcAndId(pFSubEntity.getMc(), pFSubEntity.getId()).size()>0){

                return Result.error("名称重复！");
            }
            if(devtApiSubEntityService.getOneDataByDmAndId(pFSubEntity.getDm(), pFSubEntity.getId()).size()>0){
                return Result.error("代码重复！");
            }
            devtApiSubEntityService.save(pFSubEntity);

            return Result.ok();
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error("【执行"+this.getClass().getName()+".save() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }

    }

    @RequestMapping(value = "/cancel")
    @ResponseBody
    public Result cancel(String id,HttpServletRequest request,
                                   HttpServletResponse response)throws Exception{

        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        try {
            DevtApiSubEntity pFunctionsubEntity = devtApiSubEntityService.getOneData(id).get(0);
            if(pFunctionsubEntity.getCancel()!=null&&pFunctionsubEntity.getCancel()){
                List<DevtApiTjoptEntity> pFunctiontjoptEntities= devtApiTjoptEntityService.getAllDataByIdOrDm(pFunctionsubEntity.getId());
                for (int i = 0; i < pFunctiontjoptEntities.size(); i++) {
                    DevtApiTjoptEntity pFunctiontjoptEntity = pFunctiontjoptEntities.get(i);
                    devtApiTjoptEntityService.delete(pFunctiontjoptEntity.getId());
                }
                
                List<DevtApiTjoptcheckEntity> pFunctiontjoptcheckEntities= devtApiTjoptcheckEntityService.getAllFormFieldByFormId(pFunctionsubEntity.getId());
                for (int i = 0; i < pFunctiontjoptcheckEntities.size(); i++) {
                    DevtApiTjoptcheckEntity pFunctiontjoptcheckEntity = pFunctiontjoptcheckEntities.get(i);
                    devtApiTjoptcheckEntityService.deleteOne(pFunctiontjoptcheckEntity.getId());
                }
                devtApiSubEntityService.delete(pFunctionsubEntity.getId());
            }else{
                pFunctionsubEntity.setCancel(true);
                devtApiSubEntityService.save(pFunctionsubEntity);
            }
            return Result.ok();
        }catch (Exception ex){
            ex.printStackTrace();

            logger.error("【执行"+this.getClass().getName()+".deleteKeShi() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(String id,HttpServletRequest request,
                                   HttpServletResponse response)throws Exception{

        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        try {
            devtApiSubEntityService.delete(id);
           return Result.ok();
        }catch (Exception ex){
            ex.printStackTrace();

            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }

    }
    @RequestMapping(value = "/getdata")
    @ResponseBody
    public Result getdata(String id,HttpServletRequest request,
                         HttpServletResponse response)throws Exception{

        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        try {
            List<DevtApiSubEntity> entities = devtApiSubEntityService.getOneData(id);
            if(entities.size()==0){
                return Result.error("未找到数据");
            }
            return Result.ok(entities.get(0));
        }catch (Exception ex){
            ex.printStackTrace();

            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }

    }


    @RequestMapping(value = "/export")
    public void export(@RequestParam Map<String, String> paramMap, HttpServletResponse response) throws Exception {

        String funtionidlist = paramMap.get("funtionidlist");
        if(!StringUtil.isEmptyOrLength0(funtionidlist)&&funtionidlist.endsWith(",")){
            funtionidlist=funtionidlist.substring(0,funtionidlist.length()-1);
        }
        String[] split = funtionidlist.split(",");

        TableConfig tableConfig=new TableConfig("devt_api_sub",
                "api功能基础配置表","id","",Boolean.TRUE);
        tableConfig.setSubtableList(new ArrayList<>());
        tableConfig.getSubtableList().add(new TableConfig("devt_api_tjopt",
                "api功能参数配置表","subid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_api_tjoptcheck",
                "api功能参数校验配置表","sub_id","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_api_main",
                "api业务信息配置表","id","mainid",Boolean.TRUE));

        List<TableConfig> tableConfigList=new ArrayList();
        tableConfigList.add(tableConfig);
        HashMap<String,List<Object>> dataMap=new HashMap<>();
        dataMap.put(tableConfig.getTablename(),new ArrayList<>());
        dataMap.get(tableConfig.getTablename()).addAll(Arrays.asList(split));

        DataExportUtil dataExportUtil = DataExportUtil.createDataExportUtil(jdbcTemplate.getDataSource(), true);
        String sqlContent=dataExportUtil.exportData(tableConfigList,dataMap,new ArrayList<>());
        String  contentType="text/sql";
        response.setContentType(StringUtil.isEmptyOrLength0(contentType)?"application/octet-stream":contentType);
        String functionid = funtionidlist.replaceAll(",", "_");
        functionid=functionid.indexOf("_")>0?functionid.substring(0,functionid.indexOf(",")):functionid;
        response.addHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode("API功能导出_"+functionid +".sql","UTF-8"));
        response.setCharacterEncoding("utf-8");
        InputStream inputStream=new ByteArrayInputStream(sqlContent.getBytes(StandardCharsets.UTF_8));
        byte[] byteData=new byte[1024*1024*3];
        int count=-1;
        ServletOutputStream servletOutputStream= response.getOutputStream();
        while ((count=inputStream.read(byteData))!=-1){
            servletOutputStream.write(byteData,0,count);
        }
        servletOutputStream.flush();
    }
}
